package com.hujf.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author Hujf
 * @title: SocketHandler
 * @date 2021/2/3 0003下午 5:16
 * @description: TextWebSocketFrame Web Socket text frame with assumed UTF-8 encoding  文本帧
 */
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    //全局事件执行器 是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("服务器收到来自客户端的消息： "+msg.text());
        //给客户端回消息
        channelGroup.writeAndFlush(new TextWebSocketFrame("服务器时间"+ LocalDateTime.now()+" 收到你的消息     "+msg.text()));
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        System.out.println("加入一个handler"+ctx.channel());
        channelGroup.writeAndFlush(new TextWebSocketFrame("客户端： "+ctx.channel().localAddress()+" 加入聊天3"));
        channelGroup.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("移除一个handler"+ctx.channel());
        channelGroup.writeAndFlush(new TextWebSocketFrame("客户端： "+ctx.channel().localAddress()+" 退出聊天"));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常"+cause.getMessage());
        ctx.close();
    }
}

